#include "tcpsocket.h"
#include <QStringList>

TcpSocket::TcpSocket(QObject *parent) : QObject(parent)
{
    socket=new QTcpSocket(this);
    socket->bind(8000);
    connect(socket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,SLOT(onStateChanged(QAbstractSocket::SocketState)));
    connect(socket,SIGNAL(readyRead()),this,SLOT(readData()));

}
void TcpSocket::connect_To_Host(QString ip, int port){
    if(socket->state()==QTcpSocket::ConnectedState)
        return;
    QHostAddress address(ip);
    socket->connectToHost(address,port);
}

QString TcpSocket::tcpState(){
    return this->currentState;
}
void TcpSocket::onStateChanged(QAbstractSocket::SocketState state){
    if(state==QTcpSocket::ConnectedState){
        currentState="connected";
        tcpStateChanged();
    }
    else if(state==QTcpSocket::ConnectingState){
        currentState="connecting";
        tcpStateChanged();
    }
    else if(state==QTcpSocket::ListeningState){
        currentState="listening";
        tcpStateChanged();

    }
    else{
        currentState="unConnected";
        tcpStateChanged();
        disconnected();
    }
}
QString TcpSocket::conIP(){
    return this->serverIP;
}
void TcpSocket::readData(){
    socket->waitForReadyRead(1000);
    qDebug()<<socket->readAll();
}
void TcpSocket::sendData(QString data){
    QByteArray datagram;
    datagram.append(data);
//    socket->flush();
    if(socket->state()==QTcpSocket::ConnectedState)
        socket->write(datagram.data(),datagram.length());
//    socket->waitForBytesWritten(500);
}
int TcpSocket::queryMode(){
    return this->mqueryMode;
}
void TcpSocket::setQueryMode(int mode){
    this->mqueryMode=mode;
    queryModeChanged();
}

//enviroment state
int TcpSocket::outsideLight(){
    return this->moutsideLight;
}
int TcpSocket::insideTemperlature(){
    return this->minsideTemperlature;
}
int TcpSocket::insideWest(){
    return this->minsideWest;
}

//air control
bool TcpSocket::isAirPowerOn(){
    return this->mairState.isPowerOn;
}
QString TcpSocket::currentAirMode(){
    return this->mairState.mode;
}
QString TcpSocket::currentAirSpeed(){
    return this->mairState.speed;
}
int TcpSocket::currentAirTemperlature(){
    return this->mairState.temperlature;
}
